package edu.ptu.communityplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import edu.ptu.communityplatform.common.controller.AjaxResponse;
import edu.ptu.communityplatform.common.controller.BaseController;

import edu.ptu.communityplatform.common.controller.TableInfo;
import edu.ptu.communityplatform.domain.entity.Person;
import edu.ptu.communityplatform.domain.entity.User;
import edu.ptu.communityplatform.domain.queryParam.LoginParam;
import edu.ptu.communityplatform.domain.queryParam.personParam.PersonAddParam;
import edu.ptu.communityplatform.domain.queryParam.personParam.PersonUpdateParam;
import edu.ptu.communityplatform.domain.vos.PersonPageVo;
import edu.ptu.communityplatform.domain.vos.PersonVo;
import edu.ptu.communityplatform.domain.vos.RoleVo;
import edu.ptu.communityplatform.mapping.PersonMapping;
import edu.ptu.communityplatform.service.ICarService;
import edu.ptu.communityplatform.service.IPersonService;
import edu.ptu.communityplatform.service.IRoleService;
import edu.ptu.communityplatform.service.IUserService;
import edu.ptu.communityplatform.utils.JWTUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

import static edu.ptu.communityplatform.mapping.RoleMapping.ROLE_MAPPING;

/**
 * @BelongsProject: communityPlatform
 * @BelongsPackage: edu.ptu.communityplatform.controller
 * @Author: HYJ
 * @CreateTime: 2025-04-05  02:58
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/person")
public class PersonController extends BaseController {

    @Resource
    private IPersonService personService;

    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;

    @Resource
    private ICarService carService;

    @PostMapping("/login")
    public AjaxResponse login(@RequestBody LoginParam loginParam) {

        // 校验参数
        if (loginParam.getUsername() == null || loginParam.getPassword() == null) {
            return AjaxResponse.fail("用户名或密码不能为空");
        }

        // 校验用户名和密码是否正确
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, loginParam.getUsername())
                .eq(User::getPassword, loginParam.getPassword());

        User user = userService.getOne(wrapper);

        if (user == null) {
            return AjaxResponse.fail("用户名或密码错误");
        }

        // 生成token
        String token = JWTUtil.createToken(user);

        return AjaxResponse.success("success", token);
    }

    /**
     * 添加人员信息
     *
     * @param person 人员信息
     * @return 新增结果
     */
    @PostMapping()
    public AjaxResponse add(@RequestBody PersonAddParam personAddParam) {
        //1.校验参数
        // 优化后的参数校验逻辑
        if (personAddParam.getCardId() == null) {
            return AjaxResponse.fail("身份证号不能为空");
        }
        // 合并长度和数字校验
        if (!personAddParam.getCardId().matches("^\\d{18}$")) {
            return AjaxResponse.fail("身份证号格式不正确");
        }
        if (personAddParam.getPersonName() == null || Objects.equals(personAddParam.getPersonName(), "")) {
            return AjaxResponse.fail("姓名不能为空");
        }
        if (personAddParam.getPhoneNumber() == null) {
            return AjaxResponse.fail("手机号不能为空");
        }
        // 更精确的手机号正则
        if (!personAddParam.getPhoneNumber().matches("^1[3-9]\\d{9}$")) {
            return AjaxResponse.fail("手机号格式不正确");
        }
        if (personAddParam.getRoleId() == null) {
            return AjaxResponse.fail("员工类型不能为空");
        }


        //2.新增人员信息
        Person person = new Person();
        person.setPersonName(personAddParam.getPersonName());
        person.setPhoneNumber(personAddParam.getPhoneNumber());
        person.setCardId(personAddParam.getCardId());
        person.setRoleId(personAddParam.getRoleId());
        person.setPlotId(personAddParam.getPlotId());

        // 调用服务层方法进行新增
        boolean result = personService.save(person);

        return result ? AjaxResponse.success("新增成功") : AjaxResponse.fail("新增失败");
    }

    /**
     * 查询小区人员详细
     *
     * @param personId 人员ID
     * @return 人员信息
     */
    @GetMapping("/dtl/{personId}")
    public AjaxResponse getDtlById(@PathVariable Long personId) {

        //
        Person person = personService.getById(personId);
        String roleName = roleService.getRoleNameByRoleId(person.getRoleId());


        // 将Person实体转换为VO对象
        PersonVo personVo = PersonMapping.PERSON_MAPPING.personToPersonVo(person);
        personVo.setRoleName(roleName);

        return person != null ? AjaxResponse.success(personVo) : AjaxResponse.fail("查询失败");
    }

    /**
     * 根据ID修改人员信息
     *
     * @param person 人员信息
     * @return 修改结果
     */
    @PutMapping()
    public AjaxResponse update(@RequestBody PersonUpdateParam personUpdateParam) {
        // 校验参数
        if (personUpdateParam.getPersonName() == null || Objects.equals("", personUpdateParam.getPersonName())) {
            return AjaxResponse.fail("姓名不能为空");
        }

        if (personUpdateParam.getPhoneNumber() == null || Objects.equals("", personUpdateParam.getPhoneNumber())) {
            return AjaxResponse.fail("手机号不能为空");
        }

        if (personUpdateParam.getCardId() == null || Objects.equals("", personUpdateParam.getCardId())) {
            return AjaxResponse.fail("身份证号不能为空");
        }


        // 创建更新条件
        LambdaQueryWrapper<Person> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Person::getPersonId, personUpdateParam.getPersonId());

        // 构建更新对象
        Person person = personService.getOne(wrapper);

        // 检查是否存在该人员
        if (person == null) {
            return AjaxResponse.fail("人员不存在");
        }

        // 更新人员信息
        person.setCardId(personUpdateParam.getCardId());
        person.setPersonName(personUpdateParam.getPersonName());
        person.setPhoneNumber(personUpdateParam.getPhoneNumber());
        person.setRoleId(personUpdateParam.getRoleId());

        // 调用服务层方法进行更新
        boolean result = personService.updateById(person);
        return result ? AjaxResponse.success("修改成功") : AjaxResponse.fail("修改失败");
    }


    /**
     * 分页查询人员信息
     *
     * @param pageNum
     * @param pageSize
     * @param plotId
     * @param personName
     * @param roleId
     * @return 分页结果
     */
    @GetMapping("/list")
    public TableInfo list(
            @RequestParam(required = true, defaultValue = "1") Integer pageNum,
            @RequestParam(required = true, defaultValue = "5") Integer pageSize,
            @RequestParam(required = true) Long plotId,
            @RequestParam(required = false) String personName,
            @RequestParam(required = false) Integer roleId
    ) {

        IPage<Person> personPage = personService.getPersonPage(pageNum, pageSize, plotId, personName, roleId);

        // 将PersonPage转换为PersonPageVo
        List<PersonPageVo> pageVos = personPage.convert(PersonMapping.PERSON_MAPPING::personToPersonPageVo).getRecords();

        // 填充角色名称
        pageVos.forEach(personPageVo -> {
            String roleName = roleService.getRoleNameByRoleId(personPageVo.getRoleId());
            personPageVo.setRoleName(roleName);
        });

        return toJson(personPage != null, pageVos, pageVos.size());

    }

    /**
     * 根据ID删除人员信息
     *
     * @param personId 人员ID
     * @return 删除结果
     */
    @DeleteMapping("/{personId}")
    public AjaxResponse delete(@PathVariable Long personId) {
        // 调用服务层方法进行删除
        boolean result = personService.removeById(personId);
        return result ? AjaxResponse.success("删除成功") : AjaxResponse.fail("删除失败");
    }

    /**
     * 查询角色名称
     *
     * @return 角色名称
     */
    @GetMapping("/roleName")
    public AjaxResponse getRoleNameByRoleId() {

        // 调用服务层方法进行查询
        List<RoleVo> roleVos = ROLE_MAPPING.roleToRoleVo(roleService.list());
        return roleVos != null ? AjaxResponse.success(roleVos) : AjaxResponse.fail("查询失败");
    }
}
